//
//  YWAttachmentsView.m
//  maintain
//
//  Created by Kyo on 16/3/18.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAttachmentsView.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "UIView+Extension.h"
#import "YWattachment.h"
#import "YWResourceManager.h"
#import "YWAttachmentManager.h"
//#import "YWAlertView.h"

#define kYWPictrueWH floorf(SCREEN_WIDTH/4 - 5) - 7
#define kYWPictureMargin 10
#define kYWMaxPictureCount 6
#define kYWPictureMaxCol(count) ((count == 4) ? 2 : 3)
#define kYWPictureViewBaseTag (1200)

@interface YWAttachmentsView ()
@end

@implementation YWAttachmentsView


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //  self.backgroundColor = [UIColor redColor];
        self.opaque = YES;
        
    }
    return self;
}

- (NSUInteger)picturesCount:(NSArray*)pictures
{
    NSUInteger picturesCount = pictures.count > kYWMaxPictureCount ? kYWMaxPictureCount : pictures.count;
    return picturesCount;
}

-(void)setAttachments:(NSArray *)attachments{
    _attachments = attachments;
    NSUInteger picturesCount = [self picturesCount:attachments];
    
    while (self.subviews.count < picturesCount) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = kYWPictureViewBaseTag + self.subviews.count;
        [button addTarget:self action:@selector(handlePictuceViewTapEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton* button = self.subviews[i];
//        button.backgroundColor = [UIColor greenColor];
//        button.titleLabel.bacxkgroundColor = [UIColor redColor];
//        button.imageView.backgroundColor = [UIColor yellowColor];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = kContentFont;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
//        CGFloat imageSize = 40;
//        CGSize buttonLabelSize = CGSizeMake(kYWPictrueWH, 20);
//        CGFloat heightGap = (kYWPictrueWH-imageSize-buttonLabelSize.height)/3;
//        button.imageEdgeInsets = UIEdgeInsetsMake(heightGap,(kYWPictrueWH - imageSize)/2,0,0);
//        button.titleEdgeInsets = UIEdgeInsetsMake(imageSize +heightGap*2,  (kYWPictrueWH - buttonLabelSize.width) / 2  -  imageSize, 0, 0);
        if (i < picturesCount) {
            YWattachment *attachment = attachments[i];
            //根据不同的附件，显示不同的图标
            NSString *typemName = [[attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
            [button setImage:[YWAttachmentsView imageWithType:typemName] forState:UIControlStateNormal];
            [button setTitle:attachment.attachmentName forState:UIControlStateNormal];
            button.hidden = NO;
            CGFloat imageSize = 40;
            CGSize buttonLabelSize = CGSizeMake(kYWPictrueWH-10, 20);
            CGFloat heightGap = (kYWPictrueWH-imageSize-buttonLabelSize.height)/3;
            button.imageEdgeInsets = UIEdgeInsetsMake(heightGap,(kYWPictrueWH - imageSize)/2,0,0);
            button.titleEdgeInsets = UIEdgeInsetsMake(imageSize +heightGap*2,  (kYWPictrueWH - buttonLabelSize.width) / 2  -  imageSize, 0, 0);
        }
        else {
            button.hidden = YES;
        }
    }
    [self setNeedsLayout];
}
+ (UIImage*)imageWithType:(NSString*)type{
    UIImage *image = nil;
    if ([type compare:@"doc" options:NSCaseInsensitiveSearch] == NSOrderedSame|| [type compare:@"docx" options:NSCaseInsensitiveSearch]== NSOrderedSame) {
        image = [UIImage imageNamed:@"attachment_word"];
    }else if ([type compare:@"ppt" options:NSCaseInsensitiveSearch]== NSOrderedSame|| [type compare:@"pptx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_ppt"];
    }else if ([type compare:@"pdf" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_pdf"];
    }else if ([type compare:@"xls" options:NSCaseInsensitiveSearch]== NSOrderedSame||[type compare:@"xlsx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_excel"];
    }else if ([type compare:@"txt" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_txt"];
    }
    else {
        image = [UIImage imageNamed:@"attachment_unknow"];
    }
    return image;
}
+ (UIImage*)bigImageWithType:(NSString*)type{
    UIImage *image = nil;
    if ([type compare:@"doc" options:NSCaseInsensitiveSearch]== NSOrderedSame|| [type compare:@"docx" options:NSCaseInsensitiveSearch]== NSOrderedSame) {
        image = [UIImage imageNamed:@"attachment_word_big"];
    }else if ([type compare:@"ppt" options:NSCaseInsensitiveSearch]== NSOrderedSame|| [type compare:@"pptx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_ppt_big"];
    }else if ([type compare:@"pdf" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_pdf_big"];
    }else if ([type compare:@"xls" options:NSCaseInsensitiveSearch]== NSOrderedSame||[type compare:@"xlsx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_excel_big"];
    }else if ([type compare:@"txt" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_txt_big"];
    }
    else {
        image = [UIImage imageNamed:@"attachment_unknow_big"];
    }
    return image;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 设置图片的尺寸和位置
    NSUInteger picturesCount = [self picturesCount:self.attachments];
    int maxCol = kYWPictureMaxCol(picturesCount);
    for (int i = 0; i < picturesCount; i++) {
        if (i < self.subviews.count) {
            UIButton* button = self.subviews[i];
            
            int col = i % maxCol;
            button.x = col * (kYWPictrueWH + kYWPictureMargin);
            
            int row = i / maxCol;
            button.y = row * (kYWPictrueWH + kYWPictureMargin);
            button.width = kYWPictrueWH;
            button.height = kYWPictrueWH;
        }
    }
}

+ (CGSize)sizeWithCount:(NSUInteger)count
{
    if (count == 0) {
        return CGSizeMake(0, 0);
    }
    if (count > kYWMaxPictureCount) {
        count = kYWMaxPictureCount;
    }
    int maxCols = kYWPictureMaxCol(count);
    
    NSUInteger cols = (count >= maxCols) ? maxCols : count;
    CGFloat picturesW = cols * kYWPictrueWH + (cols - 1) * kYWPictureMargin;
    
    NSUInteger rows = (count + maxCols - 1) / maxCols;
    CGFloat picturesH = rows * kYWPictrueWH + (rows - 1) * kYWPictureMargin;
    
    return CGSizeMake(picturesW, picturesH);
}

- (void)sizeWithCount:(NSUInteger)count withConstraint:(NSLayoutConstraint *)largeContraint{
    if (count == 0) {
        [self removeFromSuperview];
    } else if (count > 3)
    {
        largeContraint.priority = UILayoutPriorityDefaultHigh + 1;
    }
}



- (UIViewController*)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

-(void)handlePictuceViewTapEvent:(UIButton*)sender{
    __block NSInteger tag = sender.tag-kYWPictureViewBaseTag;
    __block YWattachment *attachment = nil;
    if (tag<=self.attachments.count) {
        attachment = (YWattachment *)self.attachments[tag];
        if (attachment.localName.length>0) {
            if ([self.delegate respondsToSelector:@selector(handleAttachment:)]) {
                [self.delegate handleAttachment:attachment];
            }
        }else{
            NSString *fileSize = [YWCommonTool getFileSize:attachment.fileSize*1024];
            NSString *tip = [NSString stringWithFormat:@"文件大小: %@,%@",fileSize,NSLocalizedString(@"didDownloadInWifi", nil)];
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tip preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [sender setTitle:NSLocalizedString(@"downloading", nil) forState:UIControlStateNormal];
                NSString *typemName = [[attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
                NSString* documentName = attachment.attachmentName?:[NSString stringWithFormat:@"%@.%@", [YWCommonTool randStringId],typemName];
                NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:documentName];
                [[YWAttachmentManager shareManager] downloadFile:attachment.downLoadUrl toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (success) {
                            //保存全路径到数据库
                            attachment.localName = documentName;
                            BOOL save = [[YWAttachmentManager shareManager] updateAttachmenLocalNameWithAttachment:attachment];
                            if (save) {
                                [[NSNotificationCenter defaultCenter] postNotificationName:KPostNoticeAttachmentReflashNotification object:attachment];
                                [sender setTitle:NSLocalizedString(@"downloadSucceed", nil) forState:UIControlStateNormal];
                            }else{
                                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"downloadFailedAndTryAgain", nil)];
                                [sender setTitle:NSLocalizedString(@"downloadFailed", nil) forState:UIControlStateNormal];
                            }
                        }else{
                            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"downloadFailedAndTryAgain", nil)];
                            [sender setTitle:NSLocalizedString(@"downloadFailed", nil) forState:UIControlStateNormal];
                        }
                    });
                }];
            }]];
            [self.viewController presentViewController:alertController animated:YES completion:nil];
        }
    }
}

@end
